package org.dromara.oce.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.oce.domain.OceAdvertiserReferralRelation;
import org.dromara.oce.domain.OceMaterialEverydayCensus;
import org.dromara.oce.domain.bo.CompilePeopleRecordBo;
import org.dromara.oce.domain.bo.OceMaterialEverydayCensusBo;
import org.dromara.oce.domain.dto.CompilePeopleRecordDataDTO;
import org.dromara.oce.domain.dto.GetVideoReportDTO;
import org.dromara.oce.domain.vo.CompilePeopleRecordVo;
import org.dromara.oce.domain.vo.OceMaterialEverydayCensusVo;
import org.dromara.oce.mapper.OceMaterialEverydayCensusMapper;
import org.dromara.oce.service.CompilePeopleRecordService;
import org.dromara.oce.service.OceMaterialEverydayCensusService;
import org.dromara.oce.service.remote.OceanEngineRemoteService;
import org.dromara.system.domain.SysDept;
import org.dromara.system.mapper.SysDeptMapper;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 巨量素材每日数据统计Service业务层处理
 *
 * @author Lion Li
 * @date 2024-12-24
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OceMaterialEverydayCensusServiceImpl extends ServiceImpl<OceMaterialEverydayCensusMapper, OceMaterialEverydayCensus> implements OceMaterialEverydayCensusService {

    private final OceMaterialEverydayCensusMapper baseMapper;
    private final SysDeptMapper deptMapper;
    private final CompilePeopleRecordService compilePeopleRecordService;
    private final OceanEngineRemoteService engineRemoteService;

    /**
     * 查询巨量素材每日数据统计
     *
     * @param id 主键
     * @return 巨量素材每日数据统计
     */
    @Override
    public OceMaterialEverydayCensusVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页询编辑素材消耗统计列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 编辑素材消耗统计分页列表
     */
    @Override
    public TableDataInfo<CompilePeopleRecordDataDTO> queryEditPageList(OceMaterialEverydayCensusBo bo, PageQuery pageQuery) {
        TableDataInfo<CompilePeopleRecordDataDTO> tableDataInfo = TableDataInfo.build();
        List<CompilePeopleRecordDataDTO> dtos = new ArrayList<>();
        PageQuery pageQueryPeople = new PageQuery(pageQuery.getPageSize(), pageQuery.getPageNum());
        CompilePeopleRecordBo boPeople = new CompilePeopleRecordBo();
        boPeople.setCompileName(bo.getCompileName());
        int total = compilePeopleRecordService.queryList(boPeople).size();
        TableDataInfo<CompilePeopleRecordVo> peopleRecordDataInfo = compilePeopleRecordService.queryPageList(boPeople, pageQueryPeople);
        tableDataInfo.setTotal(total);
        List<CompilePeopleRecordVo> peopleList = peopleRecordDataInfo.getRows();
        if (CollectionUtils.isEmpty(peopleList)) {
            return tableDataInfo;
        }
        Map<String, List<OceMaterialEverydayCensus>> map = new HashMap<>();
        List<String> compileNames = peopleList.stream().map(CompilePeopleRecordVo::getCompileName).distinct().toList();
        compileNames.forEach(compileName -> {
            List<OceMaterialEverydayCensus> list = new ArrayList<>();
            map.put(compileName, list);
        });
        LambdaQueryWrapper<OceMaterialEverydayCensus> lqw = buildQueryWrapper(bo);
        List<OceMaterialEverydayCensus> vos = baseMapper.selectEditList(lqw);
        if (CollectionUtils.isNotEmpty(vos)) {
            for (OceMaterialEverydayCensus vo : vos) {
                for (String str : compileNames) {
                    boolean matches = vo.getAdPlatformMaterialName().contains(str);
                    if (matches) {
                        if (map.containsKey(str)) {
                            map.get(str).add(vo);
                            break;
                        }
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(map)) {
                for (Map.Entry<String, List<OceMaterialEverydayCensus>> entry : map.entrySet()) {
                    List<OceMaterialEverydayCensus> voList = entry.getValue();
                    BigDecimal statCost = voList.stream().map(OceMaterialEverydayCensus::getStatCost).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    int showCnt = voList.stream().map(OceMaterialEverydayCensus::getShowCnt).filter(Objects::nonNull).reduce(0, Integer::sum);
                    int clickCnt = voList.stream().map(OceMaterialEverydayCensus::getClickCnt).filter(Objects::nonNull).reduce(0, Integer::sum);
                    int convertCnt = voList.stream().map(OceMaterialEverydayCensus::getConvertCnt).filter(Objects::nonNull).reduce(0, Integer::sum);
                    BigDecimal cpmPlatform = showCnt > 0 ? statCost.divide(new BigDecimal(showCnt), 5, RoundingMode.HALF_UP).scaleByPowerOfTen(3) : BigDecimal.ZERO;
                    BigDecimal ctr = showCnt > 0 ? new BigDecimal(clickCnt).divide(new BigDecimal(showCnt), 5, RoundingMode.HALF_UP).scaleByPowerOfTen(2) : BigDecimal.ZERO;
                    BigDecimal conversionCost = convertCnt > 0 ? statCost.divide(new BigDecimal(convertCnt), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
                    CompilePeopleRecordDataDTO dto = new CompilePeopleRecordDataDTO();
                    dto.setCompileName(entry.getKey());
                    dto.setStatCost(statCost);
                    dto.setShowCnt(showCnt);
                    dto.setClickCnt(clickCnt);
                    dto.setConvertCnt(convertCnt);
                    dto.setCpmPlatform(cpmPlatform);
                    dto.setCtr(ctr);
                    dto.setConversionCost(conversionCost);
                    dtos.add(dto);
                }
                String column = pageQuery.getOrderByColumn();
                String asc = pageQuery.getIsAsc();
                if (StringUtils.isNotBlank(column)) {
                    if ("statCost".equals(column)) {
                        if ("asc".equals(asc)) {
                            dtos = dtos.stream().sorted(Comparator.comparing((CompilePeopleRecordDataDTO o) -> o.getStatCost().doubleValue())).collect(Collectors.toList());
                        } else {
                            dtos = dtos.stream().sorted(Comparator.comparing((CompilePeopleRecordDataDTO o) -> o.getStatCost().doubleValue()).reversed()).collect(Collectors.toList());
                        }
                    }
                    if ("showCnt".equals(column)) {
                        if ("asc".equals(asc)) {
                            dtos = dtos.stream().sorted(Comparator.comparing(CompilePeopleRecordDataDTO::getShowCnt)).collect(Collectors.toList());
                        } else {
                            dtos = dtos.stream().sorted(Comparator.comparing(CompilePeopleRecordDataDTO::getShowCnt).reversed()).collect(Collectors.toList());
                        }
                    }
                    if ("clickCnt".equals(column)) {
                        if ("asc".equals(asc)) {
                            dtos = dtos.stream().sorted(Comparator.comparing(CompilePeopleRecordDataDTO::getClickCnt)).collect(Collectors.toList());
                        } else {
                            dtos = dtos.stream().sorted(Comparator.comparing(CompilePeopleRecordDataDTO::getClickCnt).reversed()).collect(Collectors.toList());
                        }
                    }
                    if ("cpmPlatform".equals(column)) {
                        if ("asc".equals(asc)) {
                            dtos = dtos.stream().sorted(Comparator.comparing((CompilePeopleRecordDataDTO o) -> o.getCpmPlatform().doubleValue())).collect(Collectors.toList());
                        } else {
                            dtos = dtos.stream().sorted(Comparator.comparing((CompilePeopleRecordDataDTO o) -> o.getCpmPlatform().doubleValue()).reversed()).collect(Collectors.toList());
                        }
                    }
                    if ("ctr".equals(column)) {
                        if ("asc".equals(asc)) {
                            dtos = dtos.stream().sorted(Comparator.comparing((CompilePeopleRecordDataDTO o) -> o.getCtr().doubleValue())).collect(Collectors.toList());
                        } else {
                            dtos = dtos.stream().sorted(Comparator.comparing((CompilePeopleRecordDataDTO o) -> o.getCtr().doubleValue()).reversed()).collect(Collectors.toList());
                        }
                    }
                    if ("convertCnt".equals(column)) {
                        if ("asc".equals(asc)) {
                            dtos = dtos.stream().sorted(Comparator.comparing((CompilePeopleRecordDataDTO o) -> o.getConvertCnt().intValue())).collect(Collectors.toList());
                        } else {
                            dtos = dtos.stream().sorted(Comparator.comparing((CompilePeopleRecordDataDTO o) -> o.getConvertCnt().intValue()).reversed()).collect(Collectors.toList());
                        }
                    }
                    if ("conversionCost".equals(column)) {
                        if ("asc".equals(asc)) {
                            dtos = dtos.stream().sorted(Comparator.comparing((CompilePeopleRecordDataDTO o) -> o.getConversionCost().doubleValue())).collect(Collectors.toList());
                        } else {
                            dtos = dtos.stream().sorted(Comparator.comparing((CompilePeopleRecordDataDTO o) -> o.getConversionCost().doubleValue()).reversed()).collect(Collectors.toList());
                        }
                    }
                }
            }
        }
        tableDataInfo.setRows(dtos);
        return tableDataInfo;
    }

    /**
     * 询编辑素材消耗统计列表
     *
     * @param bo 查询条件
     * @return 编辑素材消耗统计分页列表
     */
    @Override
    public List<CompilePeopleRecordDataDTO> queryEditList(OceMaterialEverydayCensusBo bo) {
        List<CompilePeopleRecordDataDTO> dtos = new ArrayList<>();
        CompilePeopleRecordBo boPeople = new CompilePeopleRecordBo();
        boPeople.setCompileName(bo.getCompileName());
        List<CompilePeopleRecordVo> peopleList = compilePeopleRecordService.queryList(boPeople);
        if (CollectionUtils.isEmpty(peopleList)) {
            return dtos;
        }
        Map<String, List<OceMaterialEverydayCensus>> map = new HashMap<>();
        List<String> compileNames = peopleList.stream().map(CompilePeopleRecordVo::getCompileName).distinct().toList();
        compileNames.forEach(compileName -> {
            List<OceMaterialEverydayCensus> list = new ArrayList<>();
            map.put(compileName, list);
        });
        LambdaQueryWrapper<OceMaterialEverydayCensus> lqw = buildQueryWrapper(bo);
        List<OceMaterialEverydayCensus> vos = baseMapper.selectEditList(lqw);
        if (CollectionUtils.isNotEmpty(vos)) {
            for (OceMaterialEverydayCensus vo : vos) {
                for (String str : compileNames) {
                    boolean matches = vo.getAdPlatformMaterialName().contains(str);
                    if (matches) {
                        if (map.containsKey(str)) {
                            map.get(str).add(vo);
                            break;
                        }
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(map)) {
                for (Map.Entry<String, List<OceMaterialEverydayCensus>> entry : map.entrySet()) {
                    List<OceMaterialEverydayCensus> voList = entry.getValue();
                    BigDecimal statCost = voList.stream().map(OceMaterialEverydayCensus::getStatCost).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    int showCnt = voList.stream().map(OceMaterialEverydayCensus::getShowCnt).filter(Objects::nonNull).reduce(0, Integer::sum);
                    int clickCnt = voList.stream().map(OceMaterialEverydayCensus::getClickCnt).filter(Objects::nonNull).reduce(0, Integer::sum);
                    int convertCnt = voList.stream().map(OceMaterialEverydayCensus::getConvertCnt).filter(Objects::nonNull).reduce(0, Integer::sum);
                    BigDecimal cpmPlatform = showCnt > 0 ? statCost.divide(new BigDecimal(showCnt), 5, RoundingMode.HALF_UP).scaleByPowerOfTen(3) : BigDecimal.ZERO;
                    BigDecimal ctr = showCnt > 0 ? new BigDecimal(clickCnt).divide(new BigDecimal(showCnt), 5, RoundingMode.HALF_UP).scaleByPowerOfTen(2) : BigDecimal.ZERO;
                    BigDecimal conversionCost = convertCnt > 0 ? statCost.divide(new BigDecimal(convertCnt), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
                    CompilePeopleRecordDataDTO dto = new CompilePeopleRecordDataDTO();
                    dto.setCompileName(entry.getKey());
                    dto.setStatCost(statCost);
                    dto.setShowCnt(showCnt);
                    dto.setClickCnt(clickCnt);
                    dto.setConvertCnt(convertCnt);
                    dto.setCpmPlatform(cpmPlatform);
                    dto.setCtr(ctr);
                    dto.setConversionCost(conversionCost);
                    dtos.add(dto);
                }
            }
        }
        return dtos;
    }

    /**
     * 分页查询巨量素材每日数据统计列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 巨量素材每日数据统计分页列表
     */
    @Override
    public TableDataInfo<OceMaterialEverydayCensusVo> queryPageList(OceMaterialEverydayCensusBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OceMaterialEverydayCensus> lqw = buildQueryWrapper(bo);
        lqw.groupBy(OceMaterialEverydayCensus::getMaterialId);
        Page<OceMaterialEverydayCensusVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的巨量素材每日数据统计列表
     *
     * @param bo 查询条件
     * @return 巨量素材每日数据统计列表
     */
    @Override
    public List<OceMaterialEverydayCensusVo> queryList(OceMaterialEverydayCensusBo bo) {
        LambdaQueryWrapper<OceMaterialEverydayCensus> lqw = buildQueryWrapper(bo);
        lqw.groupBy(OceMaterialEverydayCensus::getMaterialId);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OceMaterialEverydayCensus> buildQueryWrapper(OceMaterialEverydayCensusBo bo) {
//        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OceMaterialEverydayCensus> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(OceMaterialEverydayCensus::getId);
        lqw.eq(bo.getTimestamps() != null, OceMaterialEverydayCensus::getTimestamps, bo.getTimestamps());
        lqw.eq(StringUtils.isNotBlank(bo.getThatDayDate()), OceMaterialEverydayCensus::getThatDayDate, bo.getThatDayDate());
        lqw.eq(StringUtils.isNotBlank(bo.getThirdAdvertiserId()), OceMaterialEverydayCensus::getThirdAdvertiserId, bo.getThirdAdvertiserId());
        lqw.like(StringUtils.isNotBlank(bo.getThirdAdvertiserName()), OceMaterialEverydayCensus::getThirdAdvertiserName, bo.getThirdAdvertiserName());
        lqw.eq(StringUtils.isNotBlank(bo.getThirdAdvertiserAppCode()), OceMaterialEverydayCensus::getThirdAdvertiserAppCode, bo.getThirdAdvertiserAppCode());
        lqw.eq(StringUtils.isNotBlank(bo.getCdpProjectId()), OceMaterialEverydayCensus::getCdpProjectId, bo.getCdpProjectId());
        lqw.like(StringUtils.isNotBlank(bo.getCdpProjectName()), OceMaterialEverydayCensus::getCdpProjectName, bo.getCdpProjectName());
        lqw.eq(StringUtils.isNotBlank(bo.getCdpPromotionId()), OceMaterialEverydayCensus::getCdpPromotionId, bo.getCdpPromotionId());
        lqw.like(StringUtils.isNotBlank(bo.getCdpPromotionName()), OceMaterialEverydayCensus::getCdpPromotionName, bo.getCdpPromotionName());
        lqw.eq(StringUtils.isNotBlank(bo.getMaterialId()), OceMaterialEverydayCensus::getMaterialId, bo.getMaterialId());
        lqw.like(StringUtils.isNotBlank(bo.getAdPlatformMaterialName()), OceMaterialEverydayCensus::getAdPlatformMaterialName, bo.getAdPlatformMaterialName());
        lqw.eq(bo.getStatCost() != null, OceMaterialEverydayCensus::getStatCost, bo.getStatCost());
        lqw.eq(bo.getShowCnt() != null, OceMaterialEverydayCensus::getShowCnt, bo.getShowCnt());
        lqw.eq(bo.getCpmPlatform() != null, OceMaterialEverydayCensus::getCpmPlatform, bo.getCpmPlatform());
        lqw.eq(bo.getClickCnt() != null, OceMaterialEverydayCensus::getClickCnt, bo.getClickCnt());
        lqw.eq(bo.getCtr() != null, OceMaterialEverydayCensus::getCtr, bo.getCtr());
        lqw.eq(bo.getCpcPlatform() != null, OceMaterialEverydayCensus::getCpcPlatform, bo.getCpcPlatform());
        lqw.eq(bo.getConvertCnt() != null, OceMaterialEverydayCensus::getConvertCnt, bo.getConvertCnt());
        lqw.eq(bo.getConversionCost() != null, OceMaterialEverydayCensus::getConversionCost, bo.getConversionCost());
        lqw.eq(bo.getConversionRate() != null, OceMaterialEverydayCensus::getConversionRate, bo.getConversionRate());
        lqw.eq(bo.getDeepConvertCnt() != null, OceMaterialEverydayCensus::getDeepConvertCnt, bo.getDeepConvertCnt());
        lqw.eq(bo.getDeepConvertCost() != null, OceMaterialEverydayCensus::getDeepConvertCost, bo.getDeepConvertCost());
        lqw.eq(bo.getDeepConvertRate() != null, OceMaterialEverydayCensus::getDeepConvertRate, bo.getDeepConvertRate());
        lqw.eq(bo.getActive() != null, OceMaterialEverydayCensus::getActive, bo.getActive());
        lqw.eq(bo.getActiveCost() != null, OceMaterialEverydayCensus::getActiveCost, bo.getActiveCost());
        lqw.eq(bo.getActiveRate() != null, OceMaterialEverydayCensus::getActiveRate, bo.getActiveRate());
        lqw.eq(bo.getActivePay() != null, OceMaterialEverydayCensus::getActivePay, bo.getActivePay());
        lqw.eq(bo.getActivePayCost() != null, OceMaterialEverydayCensus::getActivePayCost, bo.getActivePayCost());
        lqw.eq(bo.getActivePayRate() != null, OceMaterialEverydayCensus::getActivePayRate, bo.getActivePayRate());
        lqw.eq(bo.getGamePayCount() != null, OceMaterialEverydayCensus::getGamePayCount, bo.getGamePayCount());
        lqw.eq(bo.getGamePayCost() != null, OceMaterialEverydayCensus::getGamePayCost, bo.getGamePayCost());
        lqw.eq(bo.getTotalPlay() != null, OceMaterialEverydayCensus::getTotalPlay, bo.getTotalPlay());
        lqw.eq(bo.getValidPlay() != null, OceMaterialEverydayCensus::getValidPlay, bo.getValidPlay());
        lqw.eq(bo.getValidPlayCost() != null, OceMaterialEverydayCensus::getValidPlayCost, bo.getValidPlayCost());
        lqw.eq(bo.getValidPlayRate() != null, OceMaterialEverydayCensus::getValidPlayRate, bo.getValidPlayRate());
        lqw.eq(bo.getPlayDuration3s() != null, OceMaterialEverydayCensus::getPlayDuration3s, bo.getPlayDuration3s());
        lqw.eq(bo.getValidPlayOfMille() != null, OceMaterialEverydayCensus::getValidPlayOfMille, bo.getValidPlayOfMille());
        lqw.eq(bo.getValidPlayCostOfMille() != null, OceMaterialEverydayCensus::getValidPlayCostOfMille, bo.getValidPlayCostOfMille());
        lqw.eq(bo.getPlay25FeedBreak() != null, OceMaterialEverydayCensus::getPlay25FeedBreak, bo.getPlay25FeedBreak());
        lqw.eq(bo.getPlay50FeedBreak() != null, OceMaterialEverydayCensus::getPlay50FeedBreak, bo.getPlay50FeedBreak());
        lqw.eq(bo.getPlay75FeedBreak() != null, OceMaterialEverydayCensus::getPlay75FeedBreak, bo.getPlay75FeedBreak());
        lqw.eq(bo.getPlay99FeedBreak() != null, OceMaterialEverydayCensus::getPlay99FeedBreak, bo.getPlay99FeedBreak());
        lqw.eq(StringUtils.isNotBlank(bo.getAveragePlayTimePerPlay()), OceMaterialEverydayCensus::getAveragePlayTimePerPlay, bo.getAveragePlayTimePerPlay());
        lqw.eq(bo.getPlayOverRate() != null, OceMaterialEverydayCensus::getPlayOverRate, bo.getPlayOverRate());
        lqw.eq(bo.getWifiPlayRate() != null, OceMaterialEverydayCensus::getWifiPlayRate, bo.getWifiPlayRate());
        lqw.eq(bo.getCardShow() != null, OceMaterialEverydayCensus::getCardShow, bo.getCardShow());
        lqw.eq(bo.getDyLike() != null, OceMaterialEverydayCensus::getDyLike, bo.getDyLike());
        lqw.eq(bo.getDyComment() != null, OceMaterialEverydayCensus::getDyComment, bo.getDyComment());
        lqw.eq(bo.getDyShare() != null, OceMaterialEverydayCensus::getDyShare, bo.getDyShare());
        lqw.eq(bo.getDislikeCnt() != null, OceMaterialEverydayCensus::getDislikeCnt, bo.getDislikeCnt());
        lqw.eq(bo.getReportCnt() != null, OceMaterialEverydayCensus::getReportCnt, bo.getReportCnt());
        lqw.eq(bo.getIesChallengeClick() != null, OceMaterialEverydayCensus::getIesChallengeClick, bo.getIesChallengeClick());
        lqw.eq(bo.getIesMusicClick() != null, OceMaterialEverydayCensus::getIesMusicClick, bo.getIesMusicClick());
        lqw.eq(bo.getLocationClick() != null, OceMaterialEverydayCensus::getLocationClick, bo.getLocationClick());
        lqw.like(StringUtils.isNotBlank(bo.getCompileName()), OceMaterialEverydayCensus::getAdPlatformMaterialName, bo.getCompileName());
        if (StringUtils.isNotBlank(bo.getStartDate()) && StringUtils.isNotBlank(bo.getEndDate())) {
            lqw.between(OceMaterialEverydayCensus::getThatDayDate, bo.getStartDate(), bo.getEndDate());
        }
        if (bo.getDeptId() != null) {
            List<SysDept> deptList = deptMapper.selectListByParentId(bo.getDeptId());
            List<Long> ids = StreamUtils.toList(deptList, SysDept::getDeptId);
            ids.add(bo.getDeptId());
            lqw.in(OceMaterialEverydayCensus::getDeptId, ids);
        }
        return lqw;
    }

    /**
     * 新增巨量素材每日数据统计
     *
     * @param bo 巨量素材每日数据统计
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OceMaterialEverydayCensusBo bo) {
        OceMaterialEverydayCensus add = MapstructUtils.convert(bo, OceMaterialEverydayCensus.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改巨量素材每日数据统计
     *
     * @param bo 巨量素材每日数据统计
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OceMaterialEverydayCensusBo bo) {
        OceMaterialEverydayCensus update = MapstructUtils.convert(bo, OceMaterialEverydayCensus.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OceMaterialEverydayCensus entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除巨量素材每日数据统计信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void syncAdvertiserVideoData(List<OceAdvertiserReferralRelation> batchList, String date, Long dateTimestamp) {
        LambdaQueryWrapper<OceMaterialEverydayCensus> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OceMaterialEverydayCensus::getTimestamps, dateTimestamp);
        Map<String, OceMaterialEverydayCensus> exitsMap = baseMapper.selectJobList(queryWrapper).stream().collect(Collectors.toMap(item -> (item.getThirdAdvertiserId() + "" + item.getMaterialId()), item -> item));


        List<OceMaterialEverydayCensus> saveList = new ArrayList<>();
        List<OceMaterialEverydayCensus> updateList = new ArrayList<>();
        for (OceAdvertiserReferralRelation referralRelation : batchList) {
            MDC.put("appCode", referralRelation.getThirdAdvertiserAppCode());
            List<GetVideoReportDTO> videoReport = engineRemoteService.getVideoReport(referralRelation.getThirdAdvertiserId(), date, date);
            if (CollectionUtils.isEmpty(videoReport)) {
                continue;
            }
//          log.info("《巨量》获取巨量广告主={},日期：{} 获取素材数据报表{}", referralRelation.getThirdAdvertiserId(), date, videoReport);
            for (GetVideoReportDTO videoReportDTO : videoReport) {
                if (videoReportDTO.getStatCost().compareTo(BigDecimal.ZERO) <= 0) {
                    //当总消耗小于等于0 不存入数据
                    continue;
                }
                //如果展示数不等于0才进行计算平均千次展现费用
                videoReportDTO.setCpmPlatform((null == videoReportDTO.getShowCnt() || videoReportDTO.getShowCnt() == 0) ? BigDecimal.ZERO : videoReportDTO.getStatCost().divide(BigDecimal.valueOf(videoReportDTO.getShowCnt()), 2, RoundingMode.HALF_UP).scaleByPowerOfTen(2));

                OceMaterialEverydayCensus oceMaterialEverydayCensus = exitsMap.get(videoReportDTO.getThirdAdvertiserId() + "" + videoReportDTO.getMaterialId());
                if (oceMaterialEverydayCensus != null) {
                    BeanUtil.copyProperties(videoReportDTO, oceMaterialEverydayCensus);
                    updateList.add(oceMaterialEverydayCensus);
                } else {
                    oceMaterialEverydayCensus = new OceMaterialEverydayCensus();
                    BeanUtil.copyProperties(videoReportDTO, oceMaterialEverydayCensus);
                    oceMaterialEverydayCensus.setTimestamps(dateTimestamp);
                    oceMaterialEverydayCensus.setThirdAdvertiserName(referralRelation.getThirdAdvertiserName());
                    oceMaterialEverydayCensus.setThirdAdvertiserAppCode(referralRelation.getThirdAdvertiserAppCode());
                    oceMaterialEverydayCensus.setCreateTime(LocalDateTime.now());
                    oceMaterialEverydayCensus.setDeptId(referralRelation.getDeptId());
                    saveList.add(oceMaterialEverydayCensus);
                }
                if (CollectionUtils.isNotEmpty(saveList) && saveList.size() >= 50) {
                    baseMapper.insertBatch(saveList);
                    saveList.clear();
                }
                if (CollectionUtils.isNotEmpty(updateList) && updateList.size() >= 50) {
                    baseMapper.updateBatchById(updateList);
                    updateList.clear();
                }
            }
        }
        if (CollectionUtils.isNotEmpty(saveList)) {
            baseMapper.insertBatch(saveList);
        }
        if (CollectionUtils.isNotEmpty(updateList)) {
            baseMapper.updateBatchById(updateList);
        }
    }
}
